<template>
  <div class="questions-new-container">
    <!-- 设置padding -->
    <div class="app-container">
      <el-card>
        <div class="container">
          <span v-if="$route.query.id">试题修改</span>
          <span v-else>试题录入</span>
        </div>
        <el-divider />
        <!-- 试题录入表单 -->
        <el-form
          ref="questionNewForm"
          :rules="rulesForm"
          :model="questionNewForm"
          label-width="100px"
        >
          <el-form-item label="学科" prop="subjectID">
            <el-col :span="6">
              <el-select
                v-model="questionNewForm.subjectID"
                placeholder="请选择"
                style="width: 100%"
                @change="handleSubjectChange(questionNewForm.subjectID)"
              >
                <el-option
                  v-for="item in subjectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="目录" prop="catalogID">
            <el-col :span="6">
              <el-select
                v-model="questionNewForm.catalogID"
                placeholder="请选择"
                style="width: 100%"
                prop="catalogID"
              >
                <el-option
                  v-for="el in catalogList"
                  :key="el.value"
                  :label="el.label"
                  :value="el.value"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="企业" prop="enterpriseID">
            <el-col :span="6">
              <el-select
                v-model="questionNewForm.enterpriseID"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in companyList"
                  :key="item.id"
                  :label="item.company"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <!-- 城市 -->

          <el-form-item label="城市" prop="province">
            <el-col :span="6">
              <el-col :span="12">
                <el-select
                  v-model="questionNewForm.province"
                  placeholder="请选择"
                  @change="handleProvinceChange(questionNewForm.province)"
                >
                  <el-option
                    v-for="(item, index) in provincesList"
                    :key="index"
                    :value="item"
                    :label="item"
                  ></el-option>
                </el-select>
              </el-col>
              <el-col :span="1">&nbsp;</el-col>
              <el-col :span="11">
                <el-select v-model="questionNewForm.city" placeholder="请选择">
                  <el-option
                    v-for="(item, index) in cityList"
                    :key="index"
                    :value="item"
                    :label="item"
                  ></el-option>
                </el-select>
              </el-col>
            </el-col>
          </el-form-item>

          <el-form-item label="方向" prop="direction">
            <el-col :span="6">
              <el-select
                v-model="questionNewForm.direction"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in directionList"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="题型" prop="questionType">
            <el-radio-group v-model="questionNewForm.questionType">
              <!-- 单选,多选简答 -->
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="难度" prop="difficulty">
            <el-radio-group v-model="questionNewForm.difficulty">
              <!-- 单选,多选简答 -->
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="题干" prop="question">
            <!-- bidirectional data binding（双向数据绑定） -->
            <!-- @blur  手动校验某个字段 -->
            <quill-editor
              v-model="questionNewForm.question"
              @blur="$refs.questionNewForm.validateField('question')"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item
            label="选项"
            prop="options"
            v-if="questionNewForm.questionType != 3"
          >
            <el-col :span="6">
              <el-row
                type="flex"
                :span="10"
                v-for="(item, index) in questionNewForm.options"
                :key="item.code"
              >
                <el-col :span="3">
                  <el-radio
                    v-model="radio1"
                    :label="item.code"
                    v-if="questionNewForm.questionType == 1"
                    >{{ item.code }}:</el-radio
                  >
                  <el-checkbox
                    v-model="questionNewForm.options[index].isRight"
                    v-if="questionNewForm.questionType == 2"
                    >{{ item.code }}:</el-checkbox
                  >
                </el-col>
                <el-col :span="17"><el-input v-model="item.title" /></el-col>
                <span>&nbsp;</span>
                <el-col :span="6"> <image-upload ref="imgupload" /></el-col>
              </el-row>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button
              type="danger"
              :disabled="questionNewForm.questionType != 2"
              size="mini"
              @click="addOptionClick()"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <el-form-item label="解析视频">
            <el-col :span="6">
              <el-input v-model="questionNewForm.videoURL" />
            </el-col>
          </el-form-item>
          <el-form-item label="答案解析" prop="answer">
            <quill-editor
              v-model="questionNewForm.answer"
              @blur="$refs.questionNewForm.validateField('answer')"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="题目备注">
            <el-col :span="6">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入内容"
                v-model="questionNewForm.remarks"
              >
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="试题标签" prop="tags">
            <el-col :span="6">
              <el-select
                multiple
                v-model="questionNewForm.tags"
                placeholder="请选择试题标签"
                style="width: 100%"
              >
                <el-option
                  v-for="item in tagsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button
              type="success"
              v-if="$route.query.id"
              @click="addQuestions($route.query.id)"
              >确认修改</el-button
            >
            <el-button type="primary" v-else @click="addQuestions('')"
              >确认提交</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { simple as subjectSimple } from '@/api/hmmm/subjects.js'
import { simple as catalogSimple } from '@/api/hmmm/directorys.js'
import { list as companyList } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction as directionList } from '@/api/hmmm/constants.js'
import ImageUpload from '../components/image-upload.vue'
import { simple as tagsList } from '@/api/hmmm/tags.js'
import { add as addQuestions, update, detail } from '@/api/hmmm/questions.js'
export default {
  components: { ImageUpload },
  props: {
    imgsrc: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      questionNewForm: {
        subjectID: '', // string非必须学科
        catalogID: '', // string非必须目录
        enterpriseID: '', // string非必须企业
        province: '', // string非必须城市
        city: '', // string非必须地区
        direction: '', // string非必须方向
        questionType: '1', // string非必须题型
        difficulty: '1', // string非必须难度
        question: '', // string非必须题干
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // sstring非必须题目备注
        tags: '', // string 非必须试题标签
        isPerfect: false, // 非必须是否精选题后台自动生成（忽略）
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
      },
      rulesForm: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ],
        catalogID: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ],
        enterpriseID: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: ['change'] }
        ],
        // city: [{ required: true, message: '' }],
        direction: [
          { required: true, message: '请选择方向', trigger: ['blur', 'change'] }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
        // tags: [{ required: true, message: '请输入标签' }]
      },
      radio1: '',
      multSelect: [],
      subjectList: [],
      catalogList: [],
      companyList: [],
      provincesList: [],
      cityList: [],
      directionList,
      tagsList: []
    }
  },
  async created () {
    if (this.$route.query.id) {
      // const obj = { id: 29 }
      // const { data } = await detail(obj)
      const { data } = await detail(this.$route.query)
      // console.log(data)
      this.questionNewForm = { ...data }
      this.$nextTick(() => {
        this.getCatalogList(this.questionNewForm.subjectID)
        this.questionNewForm.tags = this.questionNewForm.tags.split(',')
        this.questionNewForm.options.forEach((el) => {
          el.isRight = Boolean(el.isRight)
        })
        this.radio1 = this.questionNewForm.options.find((el) => el.isRight)?.code
        // 将返回的图片地址回显
        //  调用父组件
        // 将服务器返回的地址给到组件内的list路径8
        // console.log(this.$refs.imgupload)
        this.questionNewForm.options.forEach((el, i) => {
          const imgCpnt = this.$refs.imgupload
          imgCpnt.forEach((items, index) => {
            if (index === i) {
              // console.log(el.img)
              items.fileList.push({ url: el.img })
            }
          })
        })
      })
    }
    this.getSimpleSubject()
    this.getcompanyList()
    this.getProvincesList()
  },
  methods: {
    async getSimpleSubject () {
      const { data } = await subjectSimple()
      this.subjectList = [...data]
    },
    handleSubjectChange (subjectID) {
      this.getCatalogList(subjectID)
      this.getTagsList(subjectID)
      // 改变学科后目录和标签都清空
      this.questionNewForm.catalogID = ''
      this.questionNewForm.tags = ''
    },
    async getCatalogList (subjectID) {
      // this.questionNewForm.catalogID = ''
      if (subjectID) {
        const { data } = await catalogSimple({ subjectID })
        this.catalogList = [...data]
      } else {
        this.catalogList = ['无数据']
      }
    },
    async getcompanyList () {
      const {
        data: { items }
      } = await companyList()
      // console.log(items)
      this.companyList = [...items]
    },
    getProvincesList () {
      this.provincesList = provinces()
    },
    getCityList (province) {
      this.questionNewForm.city = ''
      if (province) {
        this.cityList = citys(province)
      } else {
        this.cityList = ['无数据']
      }
    },
    handleProvinceChange (province) {
      this.getCityList(province)
    },
    async getTagsList (subjectID) {
      if (subjectID) {
        const { data } = await tagsList({ subjectID })
        // console.log(data)
        this.tagsList = data
      } else {
        this.tagsList = ['无数据']
      }
    },
    addOptionClick () {
      const lstIndex = this.questionNewForm.options.length - 1
      const code = this.questionNewForm.options[lstIndex].code
      const num = code.charCodeAt(0)
      const obj = {
        code: '',
        title: '',
        img: '',
        isRight: false
      }
      obj.code = String.fromCharCode(num + 1)
      this.questionNewForm.options.push(obj)
    },
    addQuestions () {
      this.$refs.questionNewForm.validate(async (valid) => {
        if (!valid) return
        //  调用父组件
        // 将腾讯云中生成的头像地址给到服务器
        // console.log(this.$refs.imgupload)
        this.questionNewForm.options.forEach((el, i) => {
          const imgCpnt = this.$refs.imgupload
          imgCpnt.forEach((items, index) => {
            if (index === i) {
              el.img = items.fileList[0]?.url
            }
          })
        })
        // if (!this.$refs.staffRef.isAllImageSuccess) {
        //   return this.$message.error('图片正在上传中,请稍后再试')
        // }
        // if (this.$refs.staffRef.fileList.length <= 0) {
        //   return this.$message.error('请上传图片')
        // }
        this.questionNewForm.options.forEach((el) => {
          if (el.code === this.radio1) {
            el.isRight = true
          }
        })
        // 企业id转为字符串
        this.questionNewForm.enterpriseID.toString()
        // tags转为字符串
        this.questionNewForm.tags = this.questionNewForm.tags.join()
        if (this.$route.query.id) {
          this.questionNewForm.id = Number(this.$route.query.id)
          await update(this.questionNewForm)
          this.$message.success('恭喜您题库修改成功!')
        } else {
          await addQuestions(this.questionNewForm)
          this.$message.success('恭喜您题库录入成功!')
        }
        this.$refs.questionNewForm.resetFields()
        this.$router.push('/questions/list')
        this.questionNewForm = {
          subjectID: '', // string非必须学科
          catalogID: '', // string非必须目录
          enterpriseID: '', // string非必须企业
          province: '', // string非必须城市
          city: '', // string非必须地区
          direction: '', // string非必须方向
          questionType: '1', // string非必须题型
          difficulty: '1', // string非必须难度
          question: '', // string非必须题干
          videoURL: '', // 解析视频
          answer: '', // 答案解析
          remarks: '', // sstring非必须题目备注
          tags: '', // string 非必须试题标签
          isPerfect: false, // 非必须是否精选题后台自动生成（忽略）
          options: [
            {
              code: 'A',
              title: '',
              img: '',
              isRight: false
            },
            {
              code: 'B',
              title: '',
              img: '',
              isRight: false
            },
            {
              code: 'C',
              title: '',
              img: '',
              isRight: false
            },
            {
              code: 'D',
              title: '',
              img: '',
              isRight: false
            }
          ]
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
//vuecss样式新特性,深度选择器
/deep/ .ql-container {
  height: 200px;
}
.practice {
  vertical-align: middle !important;
}
/deep/ .el-upload-list__item {
  width: 100px;
}
</style>
